using System;
using System.Threading.Tasks;
using JlPay.Sdk.Core;
using JlPay.Sdk.Models.Openmerch.Bill;

namespace JlPay.Sdk.Services.Openmerch.Bill
{
    /// <summary>
    /// 开放商户账单服务
    /// @author liaochangyi
    /// @since 2025-01-25
    /// </summary>
    public class BillService : BaseService
    {
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="config">配置对象</param>
        public BillService(Config config) : base(config)
        {
        }

        /// <summary>
        /// 获取API URL
        /// </summary>
        /// <param name="requestClass">请求类</param>
        /// <param name="apiPath">API路径</param>
        /// <returns>完整的API URL</returns>
        private string GetApiUrl(Type requestClass, string? apiPath = null)
        {
            var baseUrl = _config.BaseUrl;

            if (!string.IsNullOrEmpty(apiPath))
            {
                return baseUrl + apiPath;
            }

            // 使用请求类中定义的API_URL
            var apiUrlField = requestClass.GetField("API_URL");
            if (apiUrlField != null)
            {
                var apiUrl = apiUrlField.GetValue(null) as string;
                if (!string.IsNullOrEmpty(apiUrl))
                {
                    return baseUrl + apiUrl;
                }
            }

            // 如果没有定义API_URL，使用默认路径
            return baseUrl + "/open/bill/download";
        }

        /// <summary>
        /// 查询账单下载
        /// </summary>
        /// <param name="request">请求对象</param>
        /// <returns>响应对象</returns>
        public async Task<BillDownloadQueryResponse> QueryBillDownloadAsync(BillDownloadQueryRequest request)
        {
            return await PostAsync<BillDownloadQueryRequest, BillDownloadQueryResponse>(request, BillDownloadQueryRequest.API_URL);
        }

        /// <summary>
        /// 结算账单查询
        /// </summary>
        /// <param name="request">请求对象</param>
        /// <returns>响应对象</returns>
        public async Task<SettleBillQueryResponse> SettleBillQueryAsync(SettleBillQueryRequest request)
        {
            return await PostAsync<SettleBillQueryRequest, SettleBillQueryResponse>(request, SettleBillQueryRequest.API_URL);
        }

        /// <summary>
        /// 订单信息查询
        /// </summary>
        /// <param name="request">请求对象</param>
        /// <returns>响应对象</returns>
        public async Task<OrderInfoQueryResponse> OrderInfoQueryAsync(OrderInfoQueryRequest request)
        {
            return await PostAsync<OrderInfoQueryRequest, OrderInfoQueryResponse>(request, OrderInfoQueryRequest.API_URL);
        }
    }
} 